package skiree.host.abetsy.config;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Order(1)
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest requestHS, HttpServletResponse response, Object handler) throws Exception {
        // 使用 ContentCachingRequestWrapper 包装请求
        ContentCachingRequestWrapper request = new ContentCachingRequestWrapper(requestHS);
        RequestContext.setRequest(request); // 存储请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ContentCachingRequestWrapper cachedRequest = RequestContext.getRequest(); // 获取请求
        String method = cachedRequest.getMethod();
        String requestURL = cachedRequest.getRequestURL().toString();

        // 打印GET请求的参数
        if ("GET".equals(method)) {
            String queryString = cachedRequest.getQueryString();
            if (queryString != null) {
                queryString = URLDecoder.decode(queryString, CharsetUtil.CHARSET_UTF_8);
                System.out.println("IP: " + getClientIpAddress(cachedRequest) + " Request: " + method + " Url: " + requestURL + "?" + queryString);
            } else {
                System.out.println("IP: " + getClientIpAddress(cachedRequest) + " Request: " + method + " Url: " + requestURL);
            }
        }

        // 打印POST请求的参数
        if ("POST".equals(method)) {
            String jsonSt = getBody(cachedRequest);
            if (JSONUtil.isTypeJSON(jsonSt)) {
                jsonSt = JSONUtil.parseObj(JSONUtil.formatJsonStr(jsonSt)).toString();
            }
            System.out.println("IP: " + getClientIpAddress(cachedRequest) + " Request: " + method + " Url: " + requestURL + " Request body: " + jsonSt);
        }

        RequestContext.clear(); // 清除请求上下文
    }

    private String getBody(ContentCachingRequestWrapper request) {
        try {
            byte[] buf = request.getContentAsByteArray();
            if (buf.length > 0) {
                return new String(buf, 0, buf.length, request.getCharacterEncoding());
            }
        } catch (Exception ignore) {}
        return "";
    }

    private String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}